from PyQt5 import QtQml
from PyQt5.QtQuick import QQuickPaintedItem
from PyQt5.QtGui import QPainter, QPen,QMouseEvent,QImage, QPixmap,QGuiApplication
from PyQt5.QtQml import qmlRegisterType
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal,QByteArray, QBuffer, QRect,Qt
from PyQt5.QtWidgets import  QWidget
import base64,json, requests

class PlayerItem(QQuickPaintedItem,QWidget):
    mySignal = pyqtSignal(int)

    def __init__(self, parent=None):
        super(PlayerItem, self).__init__(parent)
        self.url = "xxxx"
        self.img = QImage()
        self.pixmap = QPixmap(self.img)
        self.show_w = 0
        self.show_h = 0
        self.aspect = 0.0
        self.pic_x = 0
        self.pic_y = 0
        self.org_scale = 0.0  # UI未缩放时，图片显示尺寸与图片原始尺寸的比例
        self.items = []
        self.org_width = 0 # UI初始化时的宽
        self.org_height = 0 # UI初始化时的高

    def paint(self, painter: QPainter):
        if self.img.width() == 0:
            return
        self.aspect = self.img.width() / self.img.height()

        if self.aspect > 1.00:
            self.show_w = self.width()
            self.show_h = self.show_w / self.aspect
        else:
            self.show_h = self.height()
            self.show_w = self.show_h * self.aspect

        if self.show_w < self.width():
            self.pic_x = (self.width() - self.show_w) / 2

        if self.show_h < self.height():
            self.pic_y = (self.height() - self.show_h) / 2
        scale = self.show_w / self.img.width()
        print("cur scale:",scale)
        self.pixmap = QPixmap(self.img)
        painter.drawPixmap(self.pic_x, self.pic_y,  self.show_w, self.show_h, self.pixmap)

        '''
        original_width = self.pixmap.width()
        original_height = self.pixmap.height()
        target_height = self.height()
        scale_factor = target_height / original_height
        scaled_width = int(original_width * scale_factor)
        scaled_height = int(original_height * scale_factor)
        rect = painter.viewport()
        x = (rect.width() - scaled_width) // 2
        y = (rect.height() - scaled_height) // 2
        painter.drawPixmap(x, y, scaled_width, scaled_height, self.pixmap)
        '''

        return

    @pyqtSlot(str)
    def setImage(self, str):
        print("str:", str)
        self.img = QImage(str)
        byte_array = QByteArray()
        buffer = QBuffer(byte_array)
        buffer.open(QBuffer.WriteOnly)
        self.img.save(buffer, "PNG")  # 将图像保存为PNG格式到QByteArray中
        buffer.close()

        base64_str = base64.b64encode(byte_array).decode('utf-8')

        self.aspect = self.img.width() / self.img.height()

        if self.aspect > 1.00:
            self.show_w = self.width()
            self.show_h = self.show_w / self.aspect
        else:
            self.show_h = self.height()
            self.show_w = self.show_h * self.aspect

        if self.show_w < self.width():
            self.pic_x = (self.width() - self.show_w) / 2

        if self.show_h < self.height():
            self.pic_y = (self.height() - self.show_h) / 2
        self.org_scale = self.show_w / self.img.width()

        print("scalex:", self.show_w / self.img.width(), "scaley:", self.show_h / self.img.height())

        data={
            'images':[base64_str],
            'zoom':self.show_w / self.img.width()
        }

        headers = {
            'method':'post',
            'Content-Type': 'application/json',
        }

        painter = QPainter(self.img)
        painter.setPen(QPen(Qt.red, 5))
        response = requests.post(self.url, data=json.dumps(data), headers=headers)
        if response.status_code == 200:
            data = json.loads(response.text)
            self.items = data['data'][0]
            for item in self.items:
                print(item)
                w = (item['text_region'][1][0] - item['text_region'][0][0])
                h = item['text_region'][2][1] - item['text_region'][1][1]
                rect = QRect(item['text_region'][0][0]/self.org_scale,item['text_region'][0][1]/self.org_scale,w/self.org_scale,h/self.org_scale)
                print(rect)
                painter.drawRect(rect)

        else:
            print(f"请求失败，状态码：{response.status_code}")
        self.mySignal.emit(len(self.items))
        self.update()

    @pyqtSlot(int, result=str)
    def getText(self, index):
        print("text", self.items[index]["text"])
        return self.items[index]["text"]

    @pyqtSlot(int,int, int, int,result=int)
    def mousePos(self, x,y, w, h):
        print("org_w:", self.org_width, "orgy:", self.org_height)
        print("w:", w, "y:", h)
        scale = self.show_h / self.img.height() # 当前图片的缩放比例

        black_y = (h-self.show_h)/2 # 黑框的高度
        black_x = (w-self.show_w)/2 # 黑框的宽度
        x -= black_x
        x /= scale / self.org_scale #可解决ui界面缩放的问题

        y -= black_y
        y /= scale/self.org_scale   #可解决ui界面缩放的问题
        print("cur:",x, "cur:y", y, "black:", black_y, "cur:", scale)
        n = -1
        for item in self.items:
            n+=1
            if x>=item['text_region'][0][0] and x<=item['text_region'][1][0] \
                and y>=item['text_region'][1][1] and y<=item['text_region'][2][1]:
                print(item['text'], "index:", n)
                break
        return n

    @pyqtSlot(int, int)
    def setWH(self, w, h):
        self.org_width = w  # UI初始化时的宽
        self.org_height = h # UI初始化时的高

if __name__ == '__main__':
    path = 'main.qml'
    app = QGuiApplication([])
    qmlRegisterType(PlayerItem, "MyModule", 1, 0, "PlayerItem")
    engine = QtQml.QQmlApplicationEngine()
    engine.load(path)

    app.exec_()
